package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.JPAHiberDAOFactory;
import dao.entity.UserDAO;

import model.entity.role.Users;

public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UserLogin() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String command = request.getParameter("command");
		if (command != null) {
			if (command.equals("signOutL")){
				request.getSession().invalidate();
				response.sendRedirect("user_login.jsp");
			} else if (command.equals("signOutH")) {
				request.getSession().invalidate();
				response.sendRedirect("shop");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pass = request.getParameter("password");
		String userName = request.getParameter("username");
		String seperate = request.getParameter("sep");
		
		UserDAO userDAO = JPAHiberDAOFactory.getInstance().getUserDAO();
		
		Users user = userDAO.checkLogin(userName, pass);
		if(user != null)
		{
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			System.out.println(user.getGroupRole().getRoleName());
			if (user.getGroupRole().getRoleName().equals("Admin")) {
				response.sendRedirect("admin");
			} else if (user.getGroupRole().getRoleName().equals("Manager")) {
				response.sendRedirect("manager");
			} else {
				response.sendRedirect("shop/TrangChu.jsp");
			}
		} else if (seperate.equals("true")) {
			
		} else {
			
		}
	}

}
